/*
 * @Author: chenshengyu
 *  房屋基准日
 * @Date: 2019-04-10 14:44:57 
 * @Last Modified by: chenshengyu
 * @Last Modified time: 2019-04-10 14:31:14
 */
layui.config({
}).use(['element', 'table', 'tree','zlContext', 'zlPinYin', 'zlPopSourceForm', 'laydate', 'dropdown', 'zlPrint'], function (exports) {
	var $ = layui.$
        , zlContext = layui.zlContext
		, layer = layui.layer
        , form = layui.form
        , table = layui.table
        , laydate = layui.laydate
		, zlPrint = layui.zlPrint
        , zlPinYin = layui.zlPinYin
        , zlPopSourceForm = layui.zlPopSourceForm
		, zlConfig = layui.zlConfig
		, statusName = zlConfig.global.result.statusName
		, msgName = zlConfig.global.result.msgName
		, dataName = zlConfig.global.result.dataName
		, OK = zlConfig.global.result.okState
		, fullheight = 'full-30';

    var fromlayerIndex,
        isloadsearch = false,
        pingps = {
			'5758F06288714A51BDC1F1E17E3FEC4C': '润乾'
			, '385D6FF9B8344D2D86F17BF98218B74A': '帆软'
			, 'AFA32A3F2BE84226B81A2DAE6EB702F7': '快搭'
		},
		reptypes = {
			'75AF609D5C6A43CEBA584532470D3033': '普通报表'
			, 'D910CAB4442F4E9AB0B3D63D7980CF6A': '填报报表'
		},
        iconsetting = "{shiycjid:'FA045B7025C849079A5F921D7849D7AF',isOpenAdQ:false,type:'text'," +
        'coltitle:[[' +
        '{ type: "numbers", fixed: "left", title: "#" },' +
        '{ type: "radio", fixed: "left" },' +
        '{ field: "REP_MINGC", title: "名称",sort: true },' +
        '{ field: "REP_BIANH", title: "编号",sort: true },' +
        '{ field: "REP_PINP", title:"品牌", width: 100,templet: "<span>{{zlPopSourceForm.pingps[d.REP_PINP]}}</span>"},' + 
        '{ field: "REP_LEIX", title:"类型", width: 120,templet: "<span>{{zlPopSourceForm.reptypes[d.REP_LEIX]}}</span>"}]],' +
        "limit:10,formtitle:'选择报表模板',page:true, id:'RWID',name : 'REP_MINGC', method:'post',params:'{type: \"post\"}' ,dataurl:'" + layui.cache['contentPath'] + "/manager/corereport/query'}";
	//渲染报表列表
	//渲染用户列表
	tableObj = table.render({
		elem: '#tbReportConfig',
		height: fullheight,
		response: zlConfig.global.gridResponse,
		limit: 999,
        page: false,
		url: layui.cache['contentPath'] + "/manager/rpt/jzr/query",
		method: 'post',
		sortload: true,
		cols: [
			[ //表头
				{
					type: 'numbers',
					fixed: 'left',
					title: '#'
                }, 
                { 
                    type: 'checkbox', 
                    fixed: 'left' },
                {
					field: 'OBJNAME',
                    title: '名称',
					sort: true
                }, {
					field: 'OBJCODE',
                    title: '编号',
					sort: true
                }, {
				// 	field: 'REPORT_NAME',
                //     title: '报表模板',
				// 	sort: true
                // },{
					field: 'JIZR',
                    title: '基准日',
					sort: true
				}, {
					field: 'SYS_STATUS',
					title: '状态',
					unresize: true,
					templet: function (d) {
                        if("0" == d.SYS_STATUS){
                            return "未发布";
                        }else if("1" == d.SYS_STATUS){
                            return "已发布";
                        }else {
                            return "错误状态";
                        }
					}
				}, {
					fixed: 'right',
					width: 240,
					title: '操作',
					align: 'center',
					toolbar: '#barReportConfig'
				}
			]
		],
		event: {
			onRowdbClick: function (field, row) {
				gridAction.editRow(row);
			}
		}
	});
	var gridAction = {
		currentEditObj: undefined,
		gridEdit: function (row, type, readonly) {
			var readonly = readonly && readonly != 0 ? 'disabled' : '';
			var frm = [
                '<div class="site-block" lay-filter="divgridField"> <form id ="frmEditGrid" class="layui-form"  action="">'
                , '	<div class="layui-form-item layui-hide">'
				, '		<div class="layui-input-block">'
				, '			<input type="text" name="EDITTYPE" class="layui-input">'
                , '			<input type="text" name="RWID" class="layui-input">'
                , '			<input type="text" name="ORGID" class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">名称</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" maxlength="85" name="OBJNAME" ' + readonly + ' lay-verify="required" placeholder="请输入名称" class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">编号</label>'
				, '		<div class="layui-input-block">'
				, '			<input type="text" maxlength="33" name="OBJCODE" ' + readonly + ' lay-verify="required" placeholder="请输入编号" class="layui-input">'
				, '		</div>'
				, '	</div>'
				, '	<div class="layui-form-item">'
				, '		<label class="layui-form-label">基准日</label>'
				, '		<div class="layui-input-block">'
				, '	  		<input type="text" class="layui-input" name="JIZR"' + readonly + '  readonly="readonly" placeholder="yyyy-MM-dd" lay-verify="required|date">'
                , '		</div>'
                , '	</div>'
                // , ' <div class="layui-form-item">'
				// , '       <div class="layui-col-md12">'
				// , '           <label class="layui-form-label">报表模板</label>'
				// , '           <div class="layui-input-block" id="smalldiv">'
				// , '               <div name="REPORT_ID" '+ readonly +' zlcomponent lay-verify="required" class="layui-form-select zlPopSourceForm">'
				// , '               </div>'
				// , '           </div>'
				// , '       </div>'
				// , '   </div>'
                , '	<div class="layui-form-item' + (readonly == 'disabled' ? ' layui-hide"' : '"') + '>'
				, '		<div class="layui-input-block">'
				, '		  <button class="layui-btn" lay-submit lay-filter="frmEditGrid">保存</button>'
				, '		</div>'
				, '	</div>'
				, '</form></div>'
			];
			layer.open({
				type: 1,
				title: readonly == 'disabled' ? '查看' : (type == 'edit' ? '编辑' : '新增'),
				id: 'coreReportConfigLayer',
				area: ['100%', '100%'],
				content: frm.join(''),
				success: function (layero, index) {
                    laydate.render({
                        elem: $('input[name="JIZR"]')[0] //指定元素
                    });
                    // var object = eval('('+iconsetting+')')
					// if(readonly == 'disabled'){
					// 	object.edittype = 'readonly';
					// }else{
					// 	object.edittype = 'edit';
                    // }
                    // zlPopSourceForm = $.extend(zlPopSourceForm,{"pingps": pingps, "reptypes": reptypes});
					// iconsetting = JSON.stringify(object);
                    // $('div[name="REPORT_ID"]').attr('settings', iconsetting);
					if (type == 'edit') {
                        // $('div[name="REPORT_ID"]').attr('value', row.REPORT_ID);
                        zlContext.autoFill($('#frmEditGrid'), row);
						$('#frmEditGrid input[name=EDITTYPE]').val('edit');
						form.render();
					}
					else {
						/**设置隐藏属性*/
						$('#frmEditGrid input[name=EDITTYPE]').val('new');
						//由于layui是主动刷新需要重新刷新才能显示出状态
						form.render();
						$('#frmEditGrid input[name=OBJNAME]').change(function () {
							var v = $('#frmEditGrid input[name=OBJNAME]').val();
							var v1 = zlPinYin.C(v);
							$('#frmEditGrid input[name=OBJCODE]').val(v1);
							form.render();
						});
					}
					fromlayerIndex = index;
				},
				cancel: function(index, layero){
					if (type == 'edit' && readonly != 'disabled') {
						 zlContext.isFormDataChange('frmEditGrid',gridAction.currentEditObj.data, gridAction, index)
						 return false;
					}
				} 
			});
		},
		viewRow: function (row) {
			gridAction.gridEdit(row, 'edit', true);
		},
		newRow: function () {
			gridAction.gridEdit(null, 'new');
		},
		editRow: function (row) {
            if(row["SYS_STATUS"] == 1){
                zlContext.warnMsg('基准日已发布，不允许编辑');
				return;
            }
			gridAction.gridEdit(row, 'edit');
		},
		deleteRows: function (rows) {
			if (rows.length == 0) {
				zlContext.warnMsg('请选择需要删除的基准日');
				return;
            }
            var canpost = true;
			var ids = [];
			for (var i = 0; i < rows.length; i++) {
				if (rows[i].SYS_STATUS == 1) {
					zlContext.warnMsg("【" + rows[i].OBJNAME + "】已发布，不允许删除");
					canpost = false;
					return;
				}
				ids.push(rows[i].RWID);
            }
            if(canpost){
                zlContext.confirm('询问', '是否要删除选择的基准日?', function (index) {
                    var param = { ids: ids.join(",") };
                    //提交删除
                    zlContext.deletePost(layui.cache['contentPath'] + '/manager/rpt/jzr/remove', param, function (result) {
                        if (result[statusName] == OK) {
                            gridAction.refreshGrid('del')
                            zlContext.successMsg('删除成功');
                        }
                        else {
                            zlContext.errorMsg(result[msgName]);
                        }
                    });
                    layer.close(index);
                });
            }
		},
		publish: function (row) {
            if(row["SYS_STATUS"] == 1){
                zlContext.warnMsg("【" + row["OBJNAME"] + "】已发布，不能重复发布");
				return;
            }
            var param = {
                "RWID": row["RWID"],
                "PUBLISHSTRATEGY_CLASS":"com.kdayun.manager.service.impl.CoreFwReportServiceImpl"
            }
			zlContext.confirm('询问', '是否确认发布【'+ row["OBJNAME"] +'】基准日?', function (index) {
				//提交发布
				zlContext.get(layui.cache['contentPath'] + '/manager/rpt/jzr/publish', param, function (result) {
					if (result[statusName] == OK) {
						gridAction.refreshGrid('edit', result[dataName]);
						zlContext.successMsg('发布成功');
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				}, true);
				layer.close(index);
			});
        },
        checkConfig: function(args){
            //校验成功返回true，否则返回false
            var bRet = false;
            zlContext.asyncGet(layui.cache['contentPath'] + '/manager/rpt/jzr/check', args, function(result){
                if (result[statusName] == OK) {
                    bRet = true;
                }
                else {
                    zlContext.errorMsg(result[msgName]);
                    bRet = false;
                }
            });
            return bRet;
        },
		sumbit: function (fields) {
            //校验
            var editType = $('#frmEditGrid input[name=EDITTYPE]').val();
            var args = {
                "RWID": fields["RWID"],
                "OBJCODE": fields["OBJCODE"],
                "JIZR": fields["JIZR"]
            }
            var bCheck = gridAction.checkConfig(args);
            if(!bCheck){
                return false;
            }
			if (editType == 'new') {
				zlContext.put(layui.cache['contentPath'] + '/manager/rpt/jzr/add', fields, function (result) {
					if (result[statusName] == OK) {
						gridAction.refreshGrid(editType, result[dataName]);
						layer.close(fromlayerIndex);
						zlContext.successMsg('保存成功');
						return true;
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			} else if (editType == 'edit') {
				zlContext.post(layui.cache['contentPath'] + '/manager/rpt/jzr/modify', fields, function (result) {
					if (result[statusName] == OK) {
						gridAction.refreshGrid(editType, fields);
						layer.close(fromlayerIndex);
						zlContext.successMsg('保存成功');
						return true;
					} else {
						zlContext.errorMsg(result[msgName]);
					}
				});
			}
			return false;
		},
		search: function () {
			var param = {};
			if ($('#edtSeacherValue').val().length>0) {
				param['SEARCH_VALUE'] = $('#edtSeacherValue').val();
				isloadsearch = true;
			}
			layui.event('WM_USERDEF',
				zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, param);
		},
		refresh: function (node) {
			$('#edtSeacherValue').val("")
			var param = {};
			layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, param);
		},
		refreshGrid: function (type, row) {
			/**刷新行 */
			if (type == 'edit' && gridAction.currentEditObj) {
				gridAction.currentEditObj.update(row);
				gridAction.refresh(null);
			} else {
				tableObj.reload('tbReportConfig');
			}
		}
	}
	$('#btnReportRefresh').on('click', function () {
		gridAction.refresh(null);
	});
	$('#btnReportNew').on('click', function () {
		gridAction.newRow();
	});
	$('#btnReportDelete').on('click', function () {
        var checkStatus = table.checkStatus("tbReportConfig");
		var rows = checkStatus.data;
		gridAction.deleteRows(rows);
	});
	$('#btnSeacher').on('click', function () {
		gridAction.search();
	});
	$('#edtSeacherValue').on('keyup', function (event) {
		var keyCode = event.keyCode;
		if (keyCode == 13) {
			gridAction.search();
		}
		if ((keyCode == '46' || keyCode == '8' || (event.ctrlKey && keyCode == '86')) && $(this).val() == '' && isloadsearch) {
            $('#btnSeacher').trigger('click');
            isloadsearch = false;
        }
	});
	table.on('tool(tbReportConfig)', function (obj) {
		var row = obj.data; //获得当前行数据
		var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
		// var tr = obj.tr; //获得当前行 tr 的DOM对象
		if (layEvent === 'detail') { //查看
			gridAction.viewRow(row)
		} else if (layEvent === 'del') { //删除
			gridAction.currentEditObj = obj;
			gridAction.deleteRows([row]);
		} else if (layEvent === 'edit') { //编辑
			gridAction.currentEditObj = obj;
			gridAction.editRow(row);
		} else if (layEvent == 'publish') {
            gridAction.currentEditObj = obj;
			gridAction.publish(row);
		}
	});
	//提交
	form.on('submit(frmEditGrid)', function (frm) {
        if ($(frm.elem).hasClass('getField')) {
            gridAction.newFields = frm.field
            return false;
        }
		return gridAction.sumbit(frm.field);
	});
	//监听刷新的事件
	layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null, function (param) {
		var index = layer.msg('数据查询中，请稍候...', { icon: 16, time: false, shade: 0.1 });
		var loadGridData = function (tableId, url, param) {
			tableObj.reload({
				url: url
				, height: fullheight
				, page: false
				, limit: 10000
				, method: 'post'
				, where: param
				, done: function (res, curr, count) {
					layer.close(index);
				}
			});
		}
		//刷新
		loadGridData('tbReportConfig', layui.cache['contentPath'] + '/manager/rpt/jzr/query', param);
	});

	gridAction.refresh(null);
	
	$(window).on('resize', function () {
		zlContext.setMaxHeihgt(0);
	}).resize();

});